<template>
  <VPage class="app-container">
    <div class="relative" style="height: 100%">
      <CategoryWrap
        type="sku"
        @toggle="toggle"
        :show="false"
        @node-click="handleNodeClick"
      ></CategoryWrap>
      <div
        class="rightWrap"
        :style="{ 'margin-left': isShowLeft ? containerWidth + 'px' : '0px' }"
      >
        <VTable ref="tableRef" v-bind="tableOptins" class="is--line" @keyup="handleKeyUp">
          <template #form="{ form }">
            <div class="w-full">
              <el-tabs
                v-if="tabList.length"
                v-model="form.dev_status"
                @tab-click="handleClick"
              >
                <el-tab-pane
                  :label="item.label"
                  :name="item.value"
                  v-for="(item, index) in tabList"
                  :key="index"
                >
                  <template #label>
                    {{ item.label }}(<span
                      :class="
                        activeName == item.value ? 'base-text-color' : 'text-[#999999]'
                      "
                      >{{ item.count }}</span
                    >)
                  </template>
                </el-tab-pane>
              </el-tabs>
            </div>
            <el-select
              class="!w-[120px]"
              v-model="form.dev_status"
              collapse-tags
              placeholder="开发状态"
              clearable
              v-if="!activeName"
            >
              <el-option
                v-for="item in options['goods.GoodsSpu']?.[0].devStatusText"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <VGroup>
              <el-select class="selectClass !w-[120px]" v-model="form.skuRange.type">
                <el-option
                  v-for="item in skuOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
              <multi-input
                v-model="form.skuRange.value"
                placeholder="批量搜索一行一个"
                class="w-[200px!important]"
              ></multi-input>
            </VGroup>
            <multi-input
              v-model="form.spu"
              placeholder="SPU,批量搜索,一行一个"
              class="w-[200px!important]"
            ></multi-input>
            <el-input
              v-model.trim="form.sku_cn_title"
              placeholder="产品名称"
              clearable
              class="w-[200px!important]"
            />
            <el-select
              class="!w-[160px]"
              v-model="form.sku_product_type"
              collapse-tags
              placeholder="产品类型"
              clearable
            >
              <el-option
                v-for="item in options['goods.GoodsSku']?.[0].skuProductTypeText"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-select
              class="!w-[120px]"
              v-model="form.product_attribute"
              collapse-tags
              placeholder="是否多属性"
              clearable
            >
              <el-option
                v-for="item in options['goods.GoodsSpu']?.[0].productAttributeText"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-select
              class="!w-[160px]"
              v-model="form.sample_testing"
              collapse-tags
              placeholder="样品检测结果"
              clearable
            >
              <el-option
                v-for="item in options['goods.GoodsSku']?.[0].sampleTestingText"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <VGroup>
              <el-select
                class="selectClass !w-[100px]"
                v-model="form.personnelRange.type"
              >
                <el-option
                  v-for="item in personnelOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <select-personnel
                v-model="form.personnelRange.value"
                :multiple="true"
                placeholder="请选择"
              ></select-personnel>
            </VGroup>
            <VGroup>
              <el-select class="selectClass !w-[150px]" v-model="form.dateRange.type">
                <el-option
                  v-for="item in dateOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <el-date-picker
                v-model="form.dateRange.value"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="max-width: 300px"
                :default-time="defaultTime()"
              />
            </VGroup>

            <el-select
              class="!w-[150px]"
              v-model="form.is_combination"
              placeholder="是否组合SKU"
              clearable
            >
              <el-option
                v-for="item in options['goods.GoodsSku']?.[0].mainAttributeText"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>

            <VGroup>
              <el-select
                class="!w-[130px]"
                v-model="form.default_supplier_type"
                placeholder="供应商类型"
              >
                <el-option
                  v-for="item in options['goods.GoodsSku']?.[0].supplierFilterTypeText"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
              <el-select
                v-model="form.supplier_id_one"
                filterable
                remote
                reserve-keyword
                :remote-method="supplierMethod"
                :loading="optionLoading"
                style="max-width: 150px"
                placeholder="供应商"
                clearable
              >
                <el-option
                  v-for="item in supplierOption"
                  :key="item.value"
                  :label="item.supplier_name"
                  :value="item.s_id"
                ></el-option>
              </el-select>
            </VGroup>
            <VGroup>
              <el-select
                class="selectClass w-[130px]"
                v-model="form.salesStatusRange.type"
              >
                <el-option
                  v-for="item in salesStatusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <el-select
                class="!w-[150px]"
                v-model="form.salesStatusRange.value"
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="item in options['goods.GoodsSku']?.[0].salesStatusText"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </VGroup>
          </template>
          <template #high_form="{ form }">
            <div class="flex flex-wrap gap-[8px]">
              <div class="high-form-title w-full">状态查询</div>

              <VGroup>
                <el-select
                  class="selectClass w-[130px]"
                  v-model="form.supplyStatusRange.type"
                >
                  <el-option
                    v-for="item in supplyStatusOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
                <el-select
                  class="!w-[150px]"
                  v-model="form.supplyStatusRange.value"
                  placeholder="请选择"
                  clearable
                >
                  <el-option
                    v-for="item in options['goods.GoodsSku']?.[0].supplyStatusText"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </VGroup>
              <VGroup>
                <el-select
                  class="selectClass w-[130px]"
                  v-model="form.productStatusRange.type"
                >
                  <el-option
                    v-for="item in productStatusOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
                <el-select
                  v-model="form.productStatusRange.value"
                  placeholder="请选择"
                  filterable
                  style="max-width: 150px"
                  clearable
                >
                  <el-option
                    v-for="item in options['goods.GoodsSpu']?.[0].spuStatusText"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </VGroup>
              <VGroup>
                <el-select
                  class="selectClass !w-[185px]"
                  v-model="form.cleanProductStatusRange.type"
                >
                  <el-option
                    v-for="item in cleanProductStatusOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
                <el-select
                  v-model="form.cleanProductStatusRange.value"
                  placeholder="请选择"
                  filterable
                  clearable
                  style="max-width: 160px"
                >
                  <el-option
                    v-for="item in options['goods.GoodsSku']?.[0].cleanProductStatusText"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </VGroup>
              <el-select
                class="!w-[160px]"
                v-model="form.liveness"
                placeholder="新老品状态"
                filterable
                clearable
              >
                <el-option
                  v-for="item in options['goods.GoodsSkuStatistics']?.[0].livenessText"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <el-select
                class="w-40"
                v-model="form.product_level"
                placeholder="产品等级"
                filterable
                clearable
              >
                <el-option
                  v-for="item in options['goods.GoodsSku']?.[0].productLevelText"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                ></el-option>
              </el-select>
              <div class="high-form-title w-full">供应商信息</div>
              <el-select
                class="!w-[130px]"
                v-model="form.default_supplier_type"
                placeholder="供应商类型"
              >
                <el-option
                  v-for="item in options['goods.GoodsSku']?.[0].supplierFilterTypeText"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
              <el-select
                v-model="form.supplier_check_status"
                placeholder="供应商审核状态"
                class="!w-[200px]"
                multiple
                collapse-tags
                clearable
              >
                <el-option
                  v-for="item in options['goods.GoodsSkuSupplier']?.[0]
                    .purchaseCheckStatusText"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
              <select-personnel
                v-model="form.supplier_manage"
                :multiple="true"
                placeholder="供应商负责人"
              ></select-personnel>
              <el-select
                v-model="form.is_refund_tax"
                placeholder="是否退税"
                class="!w-[200px]"
                multiple
                collapse-tags
                clearable
              >
                <el-option
                  v-for="item in isRefundTaxOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
              <multi-input
                v-model="form.custom_code"
                placeholder="海关编码，批量一行一个"
                class="w-[200px!important]"
              ></multi-input>

              <el-select
                v-model="form.is_stock_prepare"
                placeholder="是否备料"
                class="!w-[200px]"
                clearable
              >
                <el-option
                  v-for="item in isStockPrepareOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
              <el-select
                v-model="form.factory_deliver"
                placeholder="是否支持工厂直发"
                class="!w-[200px]"
                clearable
              >
                <el-option
                  v-for="item in isFactoryDelivertOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
              <div class="high-form-title w-full">推荐平台/站点</div>
              <SelectPlatformSite
                v-model:platform="form.recommended_platform_name"
                valueKey="platform_code"
                v-model:site="form.recommended_site_code"
                platformPlaceholder="推荐平台"
                sitePlaceholder="推荐站点"
              >
              </SelectPlatformSite>
              <div class="high-form-title w-full">重量尺寸</div>
              <vGroup>
                <el-select class="!w-[60px]" v-model="form.packing_qty_symbol">
                  <el-option
                    v-for="item in operatorOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
                <el-input
                  class="w-40"
                  v-model.number="form.packing_qty"
                  :min="1"
                  placeholder="装箱数量"
                  oninput="value=value.replace(/[^\d]/g,'')"
                />
              </vGroup>
              <vGroup>
                <el-select class="!w-[60px]" v-model="form.cabinets_qty_symbol">
                  <el-option
                    v-for="item in operatorOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
                <el-input
                  class="w-40"
                  v-model.number="form.cabinets_qty"
                  :min="1"
                  placeholder="装柜数量"
                  oninput="value=value.replace(/[^\d]/g,'')"
                />
              </vGroup>
              <div class="high-form-title w-full">SPU类型查询</div>
              <el-select
                v-model="form.is_dangerous"
                placeholder="是否危险品"
                class="!w-[160px]"
                clearable
              >
                <el-option
                  v-for="item in whetherOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
              <el-select
                class="!w-[160px]"
                v-model="form.need_photo"
                collapse-tags
                placeholder="是否需要拍照"
                clearable
              >
                <el-option
                  v-for="item in options['goods.GoodsSpu']?.[0].needPhotoText"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <select-logistics
                class="!w-[160px]"
                v-model="form.logistics_attributes"
                placeholder="物流属性"
              ></select-logistics>
              <el-select
                class="!w-[160px]"
                v-model="form.brand_type"
                clearable
                placeholder="品牌类型"
              >
                <el-option
                  v-for="item in options['goods.GoodsSpu']?.[0].brandTypeText"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <el-select
                class="!w-[160px]"
                v-model="form.goods_source"
                collapse-tags
                placeholder="产品来源"
                clearable
              >
                <el-option
                  v-for="item in options['goods.GoodsSpu']?.[0].goodsSourceText"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <el-select
                class="!w-[160px]"
                v-model="form.recommended_level"
                collapse-tags
                placeholder="SPU等级"
                clearable
              >
                <el-option
                  v-for="item in options['goods.GoodsSpu']?.[0].recommendLevelText"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>

              <div class="high-form-title w-full">SKU类型查询</div>
              <el-select
                class="!w-[160px]"
                v-model="form.combined_sources"
                placeholder="组合类型"
                clearable
              >
                <el-option
                  v-for="item in options['goods.GoodsSpu']?.[0].combinedSourcesText"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
              <select-brand
                class="!w-[160px]"
                v-model="form.brand_id"
                :multiple="true"
                placeholder="产品品牌"
              ></select-brand>
              <el-select
                v-model="form.plug_specification"
                clearable
                placeholder="插头规格"
                class="!w-[160px]"
              >
                <el-option
                  v-for="item in options['goods.GoodsSkuSalesInfo']?.[0]
                    .plugSpecificationText"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <el-select
                v-model="form.is_new_product"
                clearable
                placeholder="是否全新件"
                class="!w-[160px]"
              >
                <el-option
                  v-for="item in options['goods.GoodsSkuSalesInfo']?.[0].isNewProductText"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <el-select
                v-model="form.is_contains_accessories"
                clearable
                placeholder="是否含有辅料"
                class="!w-[160px]"
              >
                <el-option
                  v-for="item in options['goods.GoodsSku']?.[0].isContainsAccessoriesText"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <el-select
                v-model="form.is_seasonal_product"
                clearable
                placeholder="是否季节性产品"
                class="!w-[160px]"
              >
                <el-option
                  v-for="item in options['goods.GoodsSkuSalesInfo']?.[0]
                    .isSeasonalProductText"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <el-select
                v-model="form.is_build_model"
                clearable
                placeholder="是否已建模"
                class="!w-[160px]"
              >
                <el-option
                  v-for="item in options['goods.GoodsSkuSalesInfo']?.[0].isBuildModelText"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <VGroup>
                <el-select class="selectClass !w-[140px]" v-model="form.accessor_type">
                  <el-option
                    v-for="item in accessorTypeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
                <el-select
                  class="!w-[160px]"
                  v-model="form.accessor_use"
                  placeholder="辅料用途"
                  filterable
                  clearable
                >
                  <el-option
                    v-for="item in options['goods.GoodsSku']?.[0].accessoriesUseText"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </VGroup>
              <el-select
                class="!w-[160px]"
                v-model="form.product_level"
                placeholder="产品等级"
                filterable
                clearable
              >
                <el-option
                  v-for="item in options['goods.GoodsSku']?.[0].productLevelText"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                ></el-option>
              </el-select>
              <el-select
                class="!w-[160px]"
                v-model="form.alternative_sku_type_replace"
                placeholder="是否绑定切换SKU"
                filterable
                clearable
              >
                <el-option
                  v-for="item in alternativeSKUTypeOptions"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                ></el-option>
              </el-select>
              <el-select
                class="!w-[160px]"
                v-model="form.is_custom_product"
                placeholder="是否定制品"
                filterable
                clearable
              >
                <el-option
                  v-for="item in options['goods.GoodsSku']?.[0].isCustomProductText"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                ></el-option>
              </el-select>

              <div class="high-form-title w-full">列表排序</div>
              <el-radio-group class="block" v-model="form.order_key">
                <div>
                  <el-radio label="dev_add_time" size="large"
                    >按开发添加时间<span class="ml-2 text-[#999]"
                      >注：距离当前越近，排在上面</span
                    ></el-radio
                  >
                </div>
                <div>
                  <el-radio label="sku" size="large"
                    >按系统SKU<span class="ml-2 text-[#999]"
                      >注：数字越大，排在上面</span
                    ></el-radio
                  >
                </div>
              </el-radio-group>
            </div>
          </template>
          <template #purchasingInformation="{ row }">
            <div class="text-[#333333]">
              <div class="flex">
                样品检测结果：
                <div v-if="row.sample_testing == 0">未检测</div>
                <div v-else-if="row.sample_testing == 1" class="flex items-center">
                  <svg-icon
                    icon-class="state_finish_cover1"
                    class="text-green-400"
                  />样品检测通过
                </div>

                <div v-else-if="row.sample_testing == 2" class="flex items-center">
                  <svg-icon icon-class="hint_cover1" class="text-red-400" />
                  样品检测异常
                </div>
              </div>
              <div class="flex justify-between">
                <div>
                  采购未税报价：¥
                  <span>
                    <dataAuthority
                      auth="unit_price"
                      :value="row.supplier_quotation"
                    ></dataAuthority>
                  </span>
                </div>
                <el-button type="primary" link @click="handlePurchaseRecord(row)"
                  >采购记录</el-button
                >
              </div>
              <div class="">
                采购未税价：¥
                <span>
                  <dataAuthority
                    auth="purchase_untaxed_price"
                    :value="row.purchase_untaxed_price"
                  ></dataAuthority>
                </span>
              </div>
              <div class="">
                采购含税价：¥
                <span>
                  <dataAuthority
                    auth="unit_price_tax"
                    :value="row.unit_price_tax"
                  ></dataAuthority>
                </span>
              </div>

              <div class="flex justify-between">
                <div class="flex items-center">
                  本地仓加权采购价
                  <el-tooltip class="item" effect="dark" placement="top">
                    <template #content>
                      说明<br />1、初始数据基于默认供应商报价，退税:取采购未税价；不退税：取采购未税报价
                      ；<br />
                      2、后续数据基于本地仓库加权成本（国内仓），取最大成本（排除样品仓）；<br />
                      3、在未获取到仓库加权成本前，修改默认供应商报价，将同步修改此加权成本；<br />
                      4、仓库加权成本，每天凌晨同步一次；<br />
                      5、组合SKU基于上述逻辑，按子SKU*组成量，进行计算；<br />
                      6、此成本用于运营在销售定价时进行参考，也可点击‘头程记录’查看该SKU的头程/库存数据；<br />
                    </template>
                    <svg-icon icon-class="QuestionFilled"></svg-icon> </el-tooltip
                  >：<dataAuthority
                    auth="purchase_weighted_cost"
                    :value="row.average_purchase_price"
                  ></dataAuthority>
                </div>
                <el-button type="primary" link @click="handleTcRecord(row)"
                  >头程记录</el-button
                >
              </div>
              <!-- <div class="text-xs text-gray-500">最近¥0.00 /最低¥ 0.00</div> -->
            </div>
          </template>
          <template #toolbar_btns>
            <vAuth auth="/goods/task/product/add">
              <el-dropdown
                :max-height="290"
                trigger="click"
                placement="bottom-start"
                @command="handleAdd"
              >
                <el-button type="primary">
                  新增产品
                  <i
                    style="font-size: 10px !important"
                    class="dk-iconfont icon-ArrowDown"
                  />
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                      v-for="(item, index) in addProductOptions"
                      :key="index"
                      :command="item.value"
                      >{{ item.label }}</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </vAuth>
            <vAuth auth="/goods/task/product/addCombination">
              <el-dropdown
                :max-height="290"
                trigger="click"
                placement="bottom-start"
                @command="handleCreateCombination"
              >
                <el-button>
                  新增组合SKU
                  <i
                    style="font-size: 10px !important"
                    class="dk-iconfont icon-ArrowDown"
                  />
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                      v-for="(item, index) in createCombinationOptions"
                      :key="index"
                      :command="item.value"
                      >{{ item.label }}</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </vAuth>
            <VButton auth="/goods/task/product/CreateSample" @click="handleCreateSample"
              >生成样品单</VButton
            >
            <VButton
              auth="/goods/task/product/new-product-add"
              @click="handleProductAdd()"
              >新品需求创建</VButton
            >

            <BatchOperation
              :batchOptions="batchOptions"
              :getTable="getBatchTableSelect"
            />
            <VButton auth="/goods/task/product/copy" @click="handlecopy('condition')">
              <svg-icon icon-class="copy" />按条件复制产品</VButton
            >
            <VButton
              auth="/goods/task/product/submitAudit"
              v-if="!activeName || activeName == 5"
              :loading="loadings.submitAudit"
              @click="submitAudit('submitAudit')"
              >提交审核</VButton
            >
            <VButton
              auth="/goods/task/product/audit"
              v-if="activeName == 0 || activeName == 2 || activeName == 3"
              @click="handleAudit"
              >开发审核
            </VButton>
            <VButton
              auth="/goods/task/product/delete"
              v-if="!activeName || activeName == 5"
              @click="handleDelete"
            >
              <svg-icon class="mr-1 base-red-color" icon-class="del" />删除
            </VButton>
            <VButton @click="handleWithdraw" auth="/goods/task/product/withdraw"
              >撤回审核</VButton
            >
            <VButton @click="handleLogistics" auth="/goods/task/product/logistics"
              >物流审核</VButton
            >
            <VButton @click="handleUnlock" auth="/goods/task/product/unlock"
              >批量解锁</VButton
            >

            <el-dropdown class="ml-auto" @command="commandOperate($event, row)">
              <el-button>
                导出操作<i
                  style="font-size: 10px !important"
                  class="dk-iconfont icon-ArrowDown"
              /></el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <VAuth auth="/goods/task/product/export">
                    <el-dropdown-item command="goods_spu">导出</el-dropdown-item>
                  </VAuth>
                  <VAuth auth="/goods/task/product/export-image">
                    <el-dropdown-item command="good_spu_img">导出(主图)</el-dropdown-item>
                  </VAuth>
                  <VAuth class="ml-auto" auth="/goods/task/product/supplierExport">
                    <el-dropdown-item command="goods_spu_supplier"
                      >供应商信息导出</el-dropdown-item
                    >
                  </VAuth>
                  <VAuth
                    class="ml-auto"
                    auth="/goods/task/product/export-combination-sku"
                  >
                    <el-dropdown-item command="goods_combination_export"
                      >组合SKU导出</el-dropdown-item
                    >
                  </VAuth>
                  <VAuth class="ml-auto" auth="/goods/task/product/goods_sku_accessor">
                    <el-dropdown-item command="goods_sku_accessor"
                      >关联辅料导出</el-dropdown-item
                    >
                  </VAuth>
                  <VAuth class="ml-auto" auth="/goods/task/product/goods_sku_clean_info">
                    <el-dropdown-item command="goods_sku_clean_info"
                      >清关信息导出</el-dropdown-item
                    >
                  </VAuth>
                  <VAuth
                    class="ml-auto"
                    auth="/goods/task/product/goods_supplier_log_list"
                  >
                    <el-dropdown-item command="goods_supplier_log_list"
                      >供应商历史报价导出</el-dropdown-item
                    >
                  </VAuth>
                </el-dropdown-menu>
              </template>
            </el-dropdown>

            <VButton auth="/goods/task/product/import" @click="handleImport">
              <i class="dk-iconfont icon-Download" />导入
            </VButton>
          </template>
        </VTable>
      </div>
    </div>
  </VPage>
  <Audit ref="AuditRef" @query="queryForm"></Audit>
  <SubmitAudit ref="SubmitAuditRef" @query="queryForm"></SubmitAudit>
  <DeleteDialog ref="DeleteDialogRef" @query="queryForm"></DeleteDialog>
  <el-dialog v-model="visible" title="备注" width="600" show-footer draggable>
    <p v-html="remark"></p>
    <template #footer>
      <el-button @click="visible = false">取 消</el-button>
    </template>
  </el-dialog>
  <VLog
    ref="roleLog"
    class="dialogPublic"
    :api="queryLogList"
    options="spuId"
    :isSearch="true"
  ></VLog>
  <AddCombinationSKU ref="combinationSKURef" @query="queryForm"></AddCombinationSKU>
  <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>
  <copyModal ref="copyModalRef"></copyModal>
  <LogisticsAudit ref="logisticsAuditRef" @refresh="refresh" />
  <HstoryPurchasePrice ref="historyPurchasePriceRef" />
  <productImport ref="productImportRef"></productImport>
  <ChangeDetails ref="ChangeDetailsRef"></ChangeDetails>
  <HistorySupplierPrice ref="HistorySupplierPriceRef"></HistorySupplierPrice>
  <CostDetails ref="CostDetailsRef"></CostDetails>
  <Add ref="addRef" :options="pmsOptions" @success="queryForm" />
</template>

<script setup lang="jsx" name="TaskProduct">
import {
  dateOptions,
  personnelOption,
  skuOption,
  batchOptions,
  operatorOptions,
  whetherOptions,
  salesStatusOptions,
  supplyStatusOptions,
  cleanProductStatusOptions,
  productStatusOptions,
  isRefundTaxOptions,
  addProductOptions,
  accessorTypeOptions,
  alternativeSKUTypeOptions,
  isStockPrepareOptions,
  isFactoryDelivertOptions,
  createCombinationOptions,
} from "./data.js";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox, ElSelect } from "element-plus";
import VImage from "@/components/Image/index.vue";
import Audit from "./components/AuditModal.vue";
import { getOptions, pushsaihe, pullsaihe, getBaseOptions } from "@/api/index.js";
import {
  queryProductList,
  queryLogList,
  spuStatistics,
  productStatus,
  getLock,
  batchUnlock,
  getSupplierList,
} from "./api";
import { ref, toRefs } from "vue";
import VLog from "@/components/VLog";
import SubmitAudit from "./components/SubmitAudit.vue";
import DeleteDialog from "./components/DeleteDialog.vue";
import AddCombinationSKU from "../../goods-management/components/AddCombination/index.vue";
import useUserStore from "@/store/modules/user";
import DerivedCenter from "@/components/DerivedCenter";
import CategoryWrap from "@/components/CategoryWrap";
import SelectPlatformSite from "@/components/SelectPlatformSite";
import copyModal from "./components/copyModal.vue";
import LogisticsAudit from "./components/LogisticsAudit.vue";
import HstoryPurchasePrice from "./components/HstoryPurchasePrice.vue";
import BatchOperation from "@/views/task/product/components/BatchOperation/index.vue";
import HistorySupplierPrice from "./components/HistorySupplierPrice.vue";
import productImport from "./components/productImport.vue";
import action from "@/utils/action.js";
import SelectLogistics from "@/components/SelectLogistics";
import SelectBrand from "@/components/SelectBrand";
import AccessoriesInfo from "@/components/Popover/AccessoriesInfo/index.vue"; // 辅料信息
import childCombination from "@/components/Popover/CombinationInfo/childCombination.vue"; // 组合SKU SKU子信息
import parentCombination from "@/components/Popover/CombinationInfo/parentCombination.vue"; // 组合SKU SKU父信息
import ChangeDetails from "./components/ChangeDetails.vue";
import seasonalProduct from "@/components/Popover/seasonalProduct/index.vue"; // 热卖信息
import usePublicStore from "@/store/modules/public";
import CostDetails from "./components/CostDetails";
import ToggleSKUInfo from "@/components/Popover/ToggleSKUInfo/index.vue"; // 切换SKU信息
import Add from "./components/Add/index";
import ProductLevelLog from "@/components/Popover/ProductLevelLog/index.vue";
const store = useUserStore();
const router = useRouter();
const tableRef = ref(null);
const AuditRef = ref(null);
const activeName = ref("");
const options = ref([]);
const records = ref([]);
const visible = ref(false);
const remark = ref("");
const loadings = reactive({
  submitAudit: false,
  del: false,
  submitAuditRow: false,
});
const data = reactive({
  tabList: [
    {
      label: "全部",
      value: "",
      count: 0,
    },
    {
      label: "待开发审核",
      value: 2,
      count: 0,
    },
    {
      label: "待物流审核",
      value: 3,
      count: 0,
    },
    {
      label: "审核未通过",
      value: 5,
      count: 0,
    },
  ],
  isShowLeft: false,
  containerWidth: 0,
});

const { tabList, isShowLeft, containerWidth } = toRefs(data);

provide("options", options);

const getSpuStatistics = async () => {
  try {
    const res = await spuStatistics();
    getCount(res.data);
  } catch (e) {
    throw Error(e);
  }
};
onMounted(() => {
  nextTick(() => {
    fetchOption();
    getSpuStatistics();
  });
});

const tableOptins = reactive({
  showHeaderOverflow: false,
  showOverflow: false,
  formConfig: {
    save: "product", // 必填，唯一
    data: {
      dev_status: "",
      product_category: "",
      date: { value: [], range: true, rangeKeys: ["start_time", "end_time"] }, // 日期
      group: { type: "group1", value: "" }, // 组合
      dateRange: { type: "dev_add_time", value: "", range: true },
      personnelRange: { type: "create_user", value: "" }, // 组合
      skuRange: { type: "sku", value: [], range: false },
      default_supplier_type: 1,
      packing_qty_symbol: ">",
      cabinets_qty_symbol: ">",
      salesStatusRange: { type: "sales_status", value: [], range: false },
      supplyStatusRange: { type: "supply_status", value: [], range: false },
      cleanProductStatusRange: { type: "clean_product_status", value: [], range: false },
      productStatusRange: { type: "product_status", value: [], range: false },
      accessor_type: 1,
      order_key: "dev_add_time",
      order_method: "desc",
    },
  },
  rowConfig: {
    height: 180,
  },
  columns: [
    {
      type: "checkbox",
      width: 50,
      fixed: "left",
    },
    {
      field: "name",
      title: "产品",
      width: "470",
      slots: {
        default: ({ row, level }) => {
          return (
            <div class="relative w-full">
              <div class="relative float-left" style="width:100px;">
                {row.brand_type != 1 && (
                  <div
                    class={[
                      "absolute",
                      "text-white",
                      "absolute-radius",
                      "z-10",
                      row.brand_type == 1 ? "bg-red-600" : "bg-gray-600",
                    ]}
                  >
                    {row.brand_type_text}
                  </div>
                )}
                <VImage
                  src={row.attr_img_watermark || row.attr_img}
                  width={100}
                  height={100}
                  preview={false}
                  class="cursor-pointer"
                  onClick={() => handlePreview(row)}
                ></VImage>
                {row.is_change_order && (
                  <div>
                    <el-button link onClick={() => handleViewChangeDetail(row.id)}>
                      是否变更：<span class="text-[#3487ff]">是</span>
                    </el-button>
                  </div>
                )}
              </div>
              <div class="ml-[105px]">
                <div class="flex justify-start items-center mb-2 ">
                  <div
                    class={[
                      "whitespace-nowrap",
                      "mr-2",
                      "text-[12px]",
                      "px-1",
                      `dev_status_color${row.dev_status}`,
                    ]}
                  >
                    {row.dev_status_text}
                  </div>
                  {row.product_status != 1 && (
                    <div
                      class={[
                        "mr-2",
                        "text-[12px]",
                        "px-1",
                        `color5`,
                        row.product_status == 2 ? "bg-red-600 text-white" : "",
                        "rounded-[4px]",
                      ]}
                    >
                      {row.product_status_text}
                    </div>
                  )}{" "}
                  {row.sales_status != 1 && (
                    <div
                      class={[
                        "whitespace-nowrap",
                        "mr-2",
                        "text-[12px]",
                        "px-1",
                        `sales_status${row.sales_status}`,
                      ]}
                    >
                      {row.sales_status_text}
                    </div>
                  )}
                  {row.supply_status != 1 && (
                    <div
                      class={[
                        "whitespace-nowrap",
                        "mr-2",
                        "text-[12px]",
                        "px-1",
                        `supply_status`,
                      ]}
                    >
                      {row.supply_status_text}
                    </div>
                  )}
                  {row.clean_product_status && (
                    <div
                      class={[
                        "whitespace-nowrap",
                        "mr-2",
                        "text-[12px]",
                        "px-1",
                        `clean_product_status${row.clean_product_status}`,
                      ]}
                    >
                      {row.clean_product_status_text}
                    </div>
                  )}
                </div>
                <div class="flex justify-start items-center mb-2 ">
                  {row.is_parent_combination ? (
                    <parentCombination row={row}></parentCombination>
                  ) : (
                    <div class="w-[130px]">
                      <VText title="SKU" value={row.sku} copy={true}></VText>
                    </div>
                  )}

                  <el-button type="primary" link onClick={() => handleView(row)}>
                    产品详情
                  </el-button>
                </div>
                <div class="flex justify-start items-center text-[14px]">
                  <VText title="SPU" value={row.spu} copy={true}></VText>
                </div>
                <div class="w-ful mr-2">
                  <VText title="自定义SKU" value={row.custom_sku} copy={true}></VText>
                </div>
                <div class="flex justify-start mb-1">
                  <VText value={row.spu_category_text}></VText>
                </div>
                <div class="flex justify-start flex-wrap">
                  {row.product_level && <ProductLevelLog row={row}></ProductLevelLog>}
                  {row.purchase_days && row.purchase_days > 0 ? (
                    <el-tooltip
                      class="item"
                      effect="dark"
                      content="采购天数"
                      placement="top"
                    >
                      <div class="btn-style mb-[2px]">{row.purchase_days} 天</div>
                    </el-tooltip>
                  ) : (
                    ""
                  )}
                  {row?.goods_sku_supplier?.min_order_quantity >= 0 ? (
                    <el-tooltip
                      class="item"
                      effect="dark"
                      content="起批量"
                      placement="top"
                    >
                      <div class="btn-style mb-[2px]">
                        {row.goods_sku_supplier.min_order_quantity} 件起批
                      </div>
                    </el-tooltip>
                  ) : (
                    ""
                  )}
                  {row.product_attribute == 2 ? (
                    <el-tooltip
                      class="item"
                      effect="dark"
                      content={row.product_attribute_text}
                      placement="top"
                    >
                      <div class="btn-style mb-[2px]">{row.product_attribute_text}</div>
                    </el-tooltip>
                  ) : (
                    ""
                  )}
                  <el-tooltip
                    class="item"
                    effect="dark"
                    content="物流属性"
                    placement="top"
                  >
                    <div class="btn-style mb-[2px] flex items-center">
                      {row.base_logistics_attributes?.is_dangerous ? (
                        <img
                          class="w-[15px] h-[15px] mr-1"
                          src="https://xc-goods.oss-cn-shenzhen.aliyuncs.com/20240515/data/Company/%28wei%29%2B045240188d69d8949e163fd84c2a5da50138df308.png"
                        ></img>
                      ) : (
                        ""
                      )}{" "}
                      {row.logistics_attributes_name || "--"}
                    </div>
                  </el-tooltip>
                  {row.is_contains_accessories == 1 && (
                    <AccessoriesInfo row={row}></AccessoriesInfo>
                  )}
                  {row.sample_purchase_type && row.sample_purchase_type != 1 && (
                    <el-tooltip
                      class="item"
                      effect="dark"
                      content="采购类型"
                      placement="top"
                    >
                      <div class="btn-style mb-[2px]">
                        {row.sample_purchase_type_text}
                      </div>
                    </el-tooltip>
                  )}
                  {row.goods_sku_supplier?.is_refund_tax == 2 && (
                    <el-tooltip
                      class="item"
                      effect="dark"
                      content="是否退税"
                      placement="top"
                    >
                      <div class="btn-style mb-[2px]">
                        {row.goods_sku_supplier.is_refund_tax_text || "--"}
                      </div>
                    </el-tooltip>
                  )}
                  {row.is_seasonal_product == 1 && (
                    <seasonalProduct data={row}></seasonalProduct>
                  )}
                  {row.is_new_product == 0 && (
                    <el-tooltip
                      class="item"
                      effect="dark"
                      content="是否全新件"
                      placement="top"
                    >
                      <div class="btn-style mb-[2px]">翻新件</div>
                    </el-tooltip>
                  )}
                  {row.alternative_sku_type ? (
                    <ToggleSKUInfo row={row}></ToggleSKUInfo>
                  ) : (
                    ""
                  )}
                  {Number(row.liveness) ? (
                    <el-tooltip
                      class="item"
                      effect="dark"
                      content="新老品状态"
                      placement="top"
                    >
                      <div class="btn-style mb-[2px]">
                        {row.liveness == 1 ? "新品" : row.liveness == 2 ? "老品" : ""}
                      </div>
                    </el-tooltip>
                  ) : (
                    ""
                  )}
                </div>
              </div>
              <div class="absolute top-0 right-0 flex">
                <childCombination data={row}></childCombination>
              </div>
            </div>
          );
        },
      },
    },
    {
      title: "产品名称",
      width: 350,
      slots: {
        default: ({ row, level }) => {
          return (
            <div>
              <VText line={6} value={row.sku_cn_title} copy={true}></VText>
            </div>
          );
        },
      },
    },
    {
      field: "product-type",
      title: "采购信息",
      width: "250",
      slots: {
        default: "purchasingInformation",
      },
    },
    {
      field: "product-info",
      title: "产品信息",
      width: "200",
      slots: {
        default: ({ row, level }) => {
          return (
            <div>
              <div class="">毛重：{row.gross_weight_g}g</div>
              <div class="">
                包装尺寸：{row.packing_size_cm?.length}*{row.packing_size_cm?.width}*
                {row.packing_size_cm?.height}cm
              </div>
              <div class="text-[12px] text-[#999999]">
                净重：{row.net_weight_g}g | 包裹重：{row.packing_weight_g}g
              </div>
              <div class="text-[12px] text-[#999999]">
                整箱毛重：{row.packing_gross_weight_kg}kg | 装箱数：{row.packing_qty}
              </div>
              <div class="text-[12px] text-[#999999]">
                整箱尺寸：{row.packing_qty_size_cm?.length || "0.00"}*
                {row.packing_qty_size_cm?.width || "0.00"}*
                {row.packing_qty_size_cm?.height || "0.00"}cm
              </div>
              <div class="text-[12px] text-[#999999]">
                产品尺寸：{row.product_size_cm?.length || "0.00"}*
                {row.product_size_cm?.width || "0.00"}*
                {row.product_size_cm?.height || "0.00"}cm
              </div>
            </div>
          );
        },
      },
    },
    {
      title: "人员",
      width: 480,
      slots: {
        default: ({ row }) => {
          return (
            <div className="w-full column-operator-time flex justify-start  text-[var(--base-text-color)]">
              <div className="lef w-3/6">
                <vText title="添加" value={row.create_user_text}></vText>
                <vText title="开发" value={row.developer_text}></vText>
                <vText title="采购" value={row.purchaser_text}></vText>
                <vText
                  title="供应商负责人"
                  value={row.goods_sku_supplier?.supplier_manage_text}
                ></vText>
              </div>
              <div className="lef w-3/6">
                <vText title="质检" value={row.quality_inspector_text}></vText>
                <vText title="开发审核" value={row.dev_reviewer_text}></vText>
                <vText title="物流审核" value={row.logistics_reviewer_text}></vText>
                <vText title="产品负责人" value={row.product_manage_id_text}></vText>
              </div>
            </div>
          );
        },
      },
    },
    {
      title: "时间",
      width: 240,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <div class="text-[var(--base-text-color)]">
                <span class="mr-2 text-[var(--base-sub-text-color)]">开发添加 </span>
                <span>{row.dev_add_time || " - "}</span>
              </div>
              <div class="text-[var(--base-text-color)]">
                <span class="mr-2 text-[var(--base-sub-text-color)]">开发审核 </span>
                <span>{row.dev_review_time || " - "}</span>
              </div>
              <div class="text-[var(--base-text-color)]">
                <span class="mr-2 text-[var(--base-sub-text-color)]">物流审核 </span>
                <span>{row.logistics_review_time || " - "}</span>
              </div>
              <div class="text-[#333333]">
                <span class="mr-2 text-[#666666]">检测时间 </span>
                <span>{row.sample_testing == 1 ? row.sample_detection_time : " - "}</span>
              </div>
            </div>
          );
        },
      },
    },
    {
      title: "操作",
      showOverflow: "title",
      width: 120,
      fixed: "right",
      text: "left",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <div>
                <VButton
                  auth="/goods/task/product/edit"
                  type="primary"
                  link
                  onClick={() => handleEdit(row)}
                >
                  编辑产品
                </VButton>
              </div>
              <div>
                <el-button type="primary" link onClick={() => viewLog(row.spu_id)}>
                  日志记录
                </el-button>
              </div>
              <div>
                <VButton
                  auth="/goods/task/product/copy"
                  type="primary"
                  link
                  onClick={() => handlecopy("copy", row)}
                >
                  复制产品
                </VButton>
              </div>
            </div>
          );
        },
      },
    },
  ],
  proxyConfig: {
    props: {
      result: "list",
      total: "total",
    },
    autoLoad: false,
    ajax: {
      query: ({ page, form }) => {
        if (form.alternative_sku_type_replace) {
          if (form.alternative_sku_type_replace == 2) {
            form.alternative_sku_type = [0, 2];
          } else {
            form.alternative_sku_type = form.alternative_sku_type_replace;
          }
        } else {
          form.alternative_sku_type = "";
        }
        return queryProductList({ ...form, ...page }).then((res) => {
          const list = res.data.map((i) => {
            i.hasChild = true;
            return i;
          });
          return {
            list,
            total: res.total,
          };
        });
      },
    },
  },
});

const getCount = (countList) => {
  tabList.value = tabList.value.map((i) => {
    countList.filter((j) => {
      j.dev_status = j.dev_status || "";
      if (i.value == j.key) {
        i.count = j.doc_count;
      }
    });
    return i;
  });
};

// 下拉数据
const fetchOption = () => {
  getOptions({
    name: [
      "goods.GoodsSpu",
      "goods.GoodsSku",
      "goods.GoodsSkuSalesInfo",
      "goods.GoodsSkuSupplier",
      "goods.GoodsSkuStatistics",
      "goods.GoodsSkuIdentificationProcessing",
    ],
  }).then((res) => {
    options.value = res.data;
  });
};

const pmsOptions = ref({});
const total = ref({});
Promise.all([
  getBaseOptions({ type: "purchase_demand_change" }).then((res) => res.data),
  getBaseOptions({ type: "develop_demand" }).then((res) => res.data),
  Promise.resolve({ test: [{ label: "没有数据", value: 1 }] }),
]).then((res) => {
  pmsOptions.value = res.reduce((acc, cur) => ((acc = { ...acc, ...cur }), acc), {});
});

const supplierOption = ref([]);
const optionLoading = ref(false);
const supplierMethod = async (query) => {
  if (query) {
    const { data } = await getSupplierList({
      page: 1,
      page_size: 1000,
      supplier_name: query,
    });
    supplierOption.value = data || [];
  } else {
    supplierOption.value = [];
  }
};

// 查看
const handleView = (row) => {
  router.push({
    path: "/task/product/detail",
    query: {
      spuId: row.spu_id,
      sku: row.sku,
    },
  });
};

// 编辑
const handleEdit = async (row) => {
  const { data } = await getLock({ spuId: row.spu_id });
  if (data != 0) {
    ElMessage.warning(`[${data}]正在编辑，请稍后操作；或者联系相关同事退出编辑操作。`);
    return;
  }
  router.push({
    path: "/task/product/edit",
    query: {
      spuId: row.spu_id,
      type: "edit",
      sku: row.sku,
    },
  });
};

// 删除
const handleDel = (id) => {
  ElMessageBox.confirm("此操作将永久删除该产品, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    confirmButtonClass: "btnFalses",
  }).then(() => {
    loadings.del = true;
    del({ productId: id ? [id] : records.value.map((item) => item.id) })
      .then((res) => {
        ElMessage({
          type: "success",
          message: res.message,
        });
        query();
      })
      .finally(() => {
        loadings.del = true;
      });
  });
};
// 审核
const handleAudit = () => {
  if (!isHandle()) return;
  const records = getSelectRow();
  nextTick(() => {
    const is_flag = records.every((item) => item.dev_status == 2);
    if (!is_flag) return ElMessage.warning("只能选择[待开发审核]的数据!");
    const { dev_status } = records[0];

    const spu_category = records.map((i) => i.spu_category);

    AuditRef.value.open({
      skuIds: records.map((v) => v.id),
      reviewOpinion: true,
      reviewType: dev_status == 2 ? 1 : dev_status == 3 ? 2 : 0,
      spu_category,
      developer_ids: records.map((v) => v.developer_id),
    });
  });
};

const handleCreateSample = () => {
  if (!isHandle()) return;
  const records = getSelectRow();
  if (!checkArray(records)) {
    ElMessage.error("请选择相同供应商");
    return;
  }
  const sku_ids = records.map((v) => v.id);
  const uniqueArray = [...new Set(records)];

  if (uniqueArray.length == 0) return ElMessage.error("至少选择一个产品");

  store.createSample(sku_ids);

  router.push({
    path: "/task/sample-list",
  });
};

const checkArray = (arr) => {
  // 检查数组长度是否大于0
  if (arr.length === 0) {
    return false;
  }
  // 获取第一个非零元素作为默认值
  let defaultSupplierId = 0;
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].goods_sku_supplier?.supplier_id !== 0) {
      defaultSupplierId = arr[i].goods_sku_supplier?.supplier_id;
      break;
    }
  }

  // 检查数组中的元素是否都与默认值相同且不为0
  for (let i = 0; i < arr.length; i++) {
    if (
      arr[i].goods_sku_supplier?.supplier_id !== defaultSupplierId ||
      arr[i].goods_sku_supplier?.supplier_id === 0
    ) {
      return false;
    }
  }

  return true;
};

// 复制商品
const copyModalRef = ref();
const handlecopy = (type, row) => {
  let item = {};
  if (row) {
    item = row;
  } else {
    if (!isHandle()) return;
    const records = getSelectRow();
    const uniqueArray = [...new Set(records)];
    if (uniqueArray.length > 1) return ElMessage.error("只能复制一个产品!");
    item = uniqueArray[0];
  }

  if (item.is_combination == 1) {
    ElMessage.error("组合SKU不支持复制新增，请使用‘新增组合SKU’功能");
    return;
  }

  if (type == "condition") {
    copyModalRef.value.open(item);
  } else {
    usePublicStore().setCopyCondition(false);

    router.push({
      path: "/task/product/add",
      query: {
        spuId: item.spu_id,
        sku_id: item.id,
        type: "copy",
      },
    });
  }
};

const SubmitAuditRef = ref();
// 提交审核
const submitAudit = (name, productId) => {
  const records = getSelectRow().map((i) => {
    return i.id;
  });
  const uniqueArray = [...new Set(records)];

  if (!productId) {
    if (!isHandle()) return;
  }
  const skuIds = productId ? [productId] : uniqueArray;
  SubmitAuditRef.value.open(skuIds);
};

// 批量删除
const DeleteDialogRef = ref();
const handleDelete = () => {
  if (!isHandle()) return;
  const records = getSelectRow().map((i) => {
    return i.id;
  });
  DeleteDialogRef.value.open(records);
};

const productImportRef = ref();
const handleImport = () => {
  productImportRef.value.open();
};

// 切换状态
const handleClick = (val, even) => {
  nextTick(() => {
    activeName.value = val.props.name;
    refresh();
    getSpuStatistics();
  });
};

//更新表格数据
const refresh = () => {
  tableRef?.value.$table.commitProxy("query");
};

const isHandle = () => {
  const records = getSelectRow();
  return !records.length ? ElMessage.error("请先选择行!") && false : true;
};

//获取已选中的行
const getSelectRow = () => {
  return tableRef?.value.$table.getCheckboxRecords();
};
const getBatchTableSelect = () => {
  let records = tableRef?.value.$table.getCheckboxRecords();
  return { name: "sku_ids", records };
};
//查看日志
const roleLog = ref();
const viewLog = (id) => {
  roleLog.value.open(id);
};

const queryForm = () => {
  const form = tableRef.value.getForm();
  nextTick(() => {
    tableRef.value.setForm({
      ...form,
    });
    tableRef.value.query();
  });
};

// 推送赛盒
const handlePush = (row) => {
  ElMessageBox({
    title: "推送赛盒",
    message: h("p", null, [
      h("p", { style: "height: 40px" }, `是否确认将SPU:${row.spu}数据推送到赛盒系统?`),
      h("p", { style: "color: #999999" }, `说明：`),
      h("p", { style: "color: #999999" }, `1、编辑保存后，系统将自动推送赛盒。`),
      h("p", { style: "color: #999999" }, `2、当前操作可用于推送失败时进行手动操作。`),
      h("p", { style: "color: #999999" }, `3、推送结果中记录推送赛盒操作情况。`),
    ]),
    showCancelButton: true,
    confirmButtonText: "确认",
    cancelButtonText: "取消",
  }).then(async (action) => {
    try {
      const res = await pushsaihe({
        spu_id: row.spu_id,
      });
      ElMessage.success(res.message);
    } catch (e) {
      throw Error(e);
    }
  });
};

// 拉取赛盒
const handlePull = (row) => {
  ElMessageBox({
    title: "拉取赛盒",
    message: h("p", null, [
      h(
        "p",
        { style: "height: 40px" },
        `是否确认将SPU:${row.spu}数据从赛盒系统同步至商品系统?`
      ),
      h("p", { style: "color: #999999" }, `说明：`),
      h("p", { style: "color: #999999" }, `1、系统定时三分钟同步一次赛盒数据。`),
      h(
        "p",
        { style: "color: #999999" },
        `2、当前操作为即时拉取赛盒数据，点击确认后，系统通过赛盒SKU，执行该条数据同步。`
      ),
    ]),
    showCancelButton: true,
    confirmButtonText: "确认",
    cancelButtonText: "取消",
  }).then(async (action) => {
    try {
      const res = await pullsaihe({
        spu_id: row.spu_id,
      });
      ElMessage.success(res.message);
    } catch (e) {
      throw Error(e);
    }
  });
};

// 新增组合sku
const combinationSKURef = ref();
const handleCreateCombination = (val) => {
  nextTick(() => {
    combinationSKURef.value.open(val);
  });
};

const handleNodeClick = (data) => {
  nextTick(() => {
    if (data.type == 1) {
      tableRef?.value.setFormField("spu_category", data.spu_category);
      tableRef?.value.setFormField("all_child_user", []);
    } else if (data.type == 2) {
      tableRef?.value.setFormField("spu_category", []);
      tableRef?.value.setFormField("all_child_user", data.all_child_user);
    }
    refresh();
  });
};

//撤回审核
const handleWithdraw = () => {
  if (!isHandle()) return;
  const records = getSelectRow();
  if (records?.length > 1) return ElMessage.warning("只能选择一条数据!");
  const { dev_status, id } = records[0];
  if (dev_status == 3 || dev_status == 2) {
    ElMessageBox({
      title: "撤回确认",
      message: "是否确认撤回到上一个状态?",
      showCancelButton: true,
      confirmButtonText: "确认",
      cancelButtonText: "取消",
    }).then(async (action) => {
      try {
        const { code, message } = await productStatus({ sku_ids: [id] });
        if (code != 200) return ElMessage.error(message);
        ElMessage.success(message);
        refresh();
      } catch (e) {
        throw Error(e);
      }
    });
  } else {
    return ElMessage.warning(
      "只能选择[待物流审核]和[待开发审核]的数据,才能撤回上一个状态!"
    );
  }
};
//物流审核
const logisticsAuditRef = ref();
const handleLogistics = () => {
  if (!isHandle()) return;
  const records = getSelectRow()
    .filter((item) => item.dev_status == 3)
    .map((i) => {
      return i.id;
    });
  if (records.length == 0) return ElMessage.warning("只能选择[待物流审核]的数据!");
  logisticsAuditRef.value.open(records);
};
//图片放大
const handlePreview = (row) => {
  if (!row.attr_img) {
    return ElMessage.error("无可查看图片");
  }
  router.push({
    path: "/task/product/preview",
    query: {
      id: row.id,
      sku: row.sku,
    },
  });
};

//批量解锁
const handleUnlock = () => {
  if (!isHandle()) return;
  const records = getSelectRow().map((i) => {
    return i.spu_id;
  });
  ElMessageBox({
    title: "解锁确认",
    message: "是否确认解锁?",
    showCancelButton: true,
    confirmButtonText: "确认",
    cancelButtonText: "取消",
  }).then(async (action) => {
    try {
      const { code, message } = await batchUnlock({ spuId: records });
      if (code != 200) return ElMessage.error(message);
      ElMessage.success("解锁成功!");
      refresh();
    } catch (e) {
      throw Error(e);
    }
  });
};

const handleKeyUp = (event) => {
  if (event.keyCode === 13 || event.key === "Enter") {
    queryForm();
    event.stopPropagation();
  }
};

const toggle = (val, width) => {
  isShowLeft.value = val;
  if (val) {
    containerWidth.value = width;
  }
};

const DerivedCenterRef = ref();
// 操作项
const commandOperate = (tag_name) => {
  const records = getSelectRow().map((i) => {
    return i.custom_sku;
  });

  const uniqueArray = [...new Set(records)];
  let condition = {};
  if (uniqueArray.length) {
    condition.custom_sku = uniqueArray;
  } else {
    condition = tableRef.value.getQueryForm();
  }

  if (condition.alternative_sku_type_replace) {
    if (condition.alternative_sku_type_replace == 2) {
      condition.alternative_sku_type = [0, 2];
    } else {
      condition.alternative_sku_type = condition.alternative_sku_type_replace;
    }
  } else {
    condition.alternative_sku_type = "";
  }
  DerivedCenterRef.value.open({
    tag_name,
    condition,
  });
};

const handleAdd = (value) => {
  router.push({
    path: "/task/product/add",
    query: {
      type: "add",
      sku_product_type: value,
    },
  });
};

// 查看变更单详情
const ChangeDetailsRef = ref();
const handleViewChangeDetail = (sku_id) => {
  ChangeDetailsRef.value.open(sku_id);
};

// 采购记录
const HistorySupplierPriceRef = ref();
const handlePurchaseRecord = (row) => {
  HistorySupplierPriceRef.value.open(row);
};

// 头程记录
const CostDetailsRef = ref();
const handleTcRecord = (row) => {
  CostDetailsRef.value.open(row);
};

// 新品创建
const addRef = ref();
const handleProductAdd = (id, isLook = false) => {
  addRef.value.open(id, isLook);
};
</script>
<style lang="scss">
.w-15 {
  width: 3.5rem;
  text-align: left;
  margin-left: 0 !important;
  margin-right: 12px !important;
}

.sales_status1 {
  color: #ffffff;
  background: #faad14;
  border-radius: 4px;
  padding-left: 8px;
  padding-right: 8px;
}

.sales_status2,
.sales_status4 {
  color: #ffffff;
  background: #999999;
  border-radius: 4px;
  padding-left: 8px;
  padding-right: 8px;
}

.sales_status3 {
  color: #ffffff;
  background: #e50113;
  border-radius: 4px;
  padding-left: 8px;
  padding-right: 8px;
}

.supply_status {
  color: #fff;
  background-color: #ff0000;
  padding-left: 8px;
  padding-right: 8px;
  border-radius: 4px;
  box-sizing: border-box;
}

.clean_product_status1 {
  color: #fff;
  background-color: #00ac76;
  padding-left: 8px;
  padding-right: 8px;
  border-radius: 4px;
  box-sizing: border-box;
}
.clean_product_status2 {
  color: #fff;
  background-color: #999999;
  padding-left: 8px;
  padding-right: 8px;
  border-radius: 4px;
  box-sizing: border-box;
}

.clean_product_status3 {
  color: #fff;
  background-color: #ff0000;
  padding-left: 8px;
  padding-right: 8px;
  border-radius: 4px;
  box-sizing: border-box;
}
</style>
<style lang="scss" scoped>
.absolute-radius {
  border-radius: 5px 0px 5px 0px;
  font-size: 12px;
  transform: scale(0.8, 0.8);
  padding: 1px 2px;
  line-height: 20px;
  text-align: center;
  left: -3px;
  top: -2px;
}

:deep(.el-tabs__nav-wrap::after) {
  height: 1px;
}

:deep(.row--level-1) {
  .col--checkbox {
    visibility: hidden;
  }
}

.selectClass {
  &:deep(.el-select__wrapper) {
    background-color: var(--base-small-bg-color) !important;
  }
}

:deep(.vx-table__form-content) {
  padding-top: 0;
}

:deep(.el-tabs__header) {
  margin-bottom: 0;
}

.high-form-title {
  font-size: 16px;
  font-weight: bold;
  color: #0a1431;
  padding: 4px 10px;
  display: flex;
  align-items: center;
  position: relative;
}

.high-form-title::before {
  content: "";
  position: absolute;
  left: 0;
  right: 0;
  width: 2px;
  height: 20px;
  background-color: #3487ff;
}
</style>
